<template>
  <div class="app-container" style="padding:0">
    <div style="width:300px;height:calc(100vh - 200px);float:left;box-shadow: 0 0 5px rgba(0,0,0,0.1);margin-top: 20px;">
      <div style="padding:8px;border-bottom:1px solid #eee;">
        <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="keyword" size="small" @input="getGoodsSnList"> </el-input>
      </div>
      <div style="height:calc(100% - 50px);overflow-y: auto">
          <div class="goodsSn-item" :class="{'choose': listQuery.goodsSn == ''}" @click="changeItem('')">全部</div>
          <div class="goodsSn-item" :class="{'choose': listQuery.goodsSn == item.name}" @click="changeItem(item)" v-for="item in goodsSnList"><i class="el-icon-success" style="color:#67c23a;font-size:14px;padding-right:2px" v-if="item.isUpdate == 1"></i><span>{{ item.name}}</span></div>
      </div>
    </div>
    <div style="width:calc(100% - 300px);float:left;padding-left:20px;padding-top:20px;">
      <div>
        <!--搜索-->
        <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
          <el-form-item label="日期：">
            <el-date-picker
              @change="handleSearchList"
              :picker-options="pickerOptions"
              v-model="listQuery.priceDate"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="showPop('add')"
              type="primary">
              新增行情
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div id="myChart" style="height:300px;" v-if="listQuery.goodsSn != ''"></div>

      <!--数据列表-->
      <div class="table-container">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column  label="日期"  align="center" min-width="100">
            <template slot-scope="scope">
              {{scope.row.priceDate}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品牌号" min-width="100">
            <template slot-scope="scope">
              {{scope.row.goodsSn}}
            </template>
          </el-table-column>
          <el-table-column label="标准报价" align="center" min-width="100">
            <template slot-scope="scope">
              {{scope.row.standardPrice}}
            </template>
          </el-table-column>
          <el-table-column min-width="100" label="市场报价" align="center">
            <template slot-scope="scope">
              {{scope.row.marketPrice}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            min-width="100"
            label="报价人">
            <template  slot-scope="scope">
                {{scope.row.userName}}
            </template>
          </el-table-column>
          <el-table-column
            min-width="200"
            header-align="center"
            align="center"
            label="备注">
            <template  slot-scope="scope">
                <div>工厂产能：{{scope.row.factoryCapacity}}</div>
                <div>工厂库存：{{scope.row.factoryStock}}</div>
                <div>{{scope.row.isFactoryRepair == 1 ? '有检修' : '无检修'}}</div>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            min-width="150"
            label="创建时间">
            <template  slot-scope="scope">
              {{scope.row.createdAt}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            min-width="150"
            label="更新时间">
            <template  slot-scope="scope">
              {{scope.row.updatedAt}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            width="150"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="showPop('edit',scope.row)">编辑</el-button>
              <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10,15,20,50,100]"
          :total="count">
        </el-pagination>
      </div>
    </div>

    <!--新增行情-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="420px">
      <el-form :model="form" size="mini" label-width="120px" ref="form" :rules="rules">
        <el-form-item label="商品牌号：" prop="goodsSn" v-if="popType == 'add'">
          <el-select filterable placeholder="请选择" clearable  v-model="form.goods" @change="changeGoodsSn" value-key="name">
              <el-option :label="item.name" :value="item" v-for="item in goodsSnList" :key="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品牌号：" v-else>
             {{form.goodsName}} / {{form.goodsSn}}
        </el-form-item>
        <el-form-item label="今日标准价：">
          {{form.standardPrice}}
          <span style="padding-left:20px;font-size:12px;color:#999" v-if="formula != ''">计算公式：{{formula}}</span>
        </el-form-item>
        <el-form-item label="今日市场报价：" prop="marketPrice">
          <el-input v-model="form.marketPrice"></el-input>
        </el-form-item>
        <el-form-item label="工厂产能：">
          <el-input v-model="form.factoryCapacity"></el-input>
        </el-form-item>
        <el-form-item label="工厂库存：">
          <el-input v-model="form.factoryStock"></el-input>
        </el-form-item>
        <el-form-item label="是否有检修：">
           <el-radio-group v-model="form.isFactoryRepair">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
           </el-radio-group>
        </el-form-item>
        <el-form-item label="检修期限：">
          <el-input v-model="form.repairRemark"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="form.notes" type="textarea" :rows="2" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>

import {getOrderUsersList,} from '@/api/partner'
import {priceDataList,editPurchasePrice,myPurchaseGoodSn,priceStatistics,calculatePrice,deletePriceData} from '@/api/company'
import {formatDate} from '@/utils/date';

const defaultListQuery={
  tab:'my',
  "priceDate" : [], //日期
  'goodsSn':'',
  "pageNum" : 1,
  "pageSize" : 10
};
const defaultForm = {
  goodsSn: '',
  standardPrice: '',
  marketPrice:'',
  factoryCapacity:'',
  factoryStock:'',
  isFactoryRepair:'',
  repairRemark:'',
  ppId:0,
  notes:'',
  goodsName:'',
  goods:''
}

export default {
  name: "market",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      keyword:'',
      pickerOptions: {
        shortcuts: [{
          text: '上个月',
          onClick(picker) {
            let now = new Date();
            let nowMonth = now.getMonth(); //当前月
            let nowYear = now.getFullYear(); //当前年
            if (nowMonth == 0) {   //如果是0，则说明是1月份，上一个月就是去年的12月
              nowYear -= 1;
              nowMonth = 11;
            }else{
              nowMonth = nowMonth - 1
            }
            //上月的开始时间
            let monthStartDate = new Date(nowYear, nowMonth, 1);
            //上月的结束时间
            let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
            let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
            let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
            picker.$emit('pick', [startDate, endDate]);
          },
        },{
          text: '近三个月',
          onClick(picker) {
            let date = new Date();
            let endDate = formatDate(new Date(), 'yyyy-MM-dd');
            let startTime = date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);
            let startDate = formatDate(new Date(startTime), 'yyyy-MM-dd')
            picker.$emit('pick', [startDate, endDate]);
          },
        }]
      },
      dialogVisible:false,
      btnLoading:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      rules:{
        goodsSn : [{required: true, message: '此项必填', trigger: 'change'},],
        marketPrice:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      popType:'',
      goodsSnList:[],
      formula:'',
      title:'',
      goods: '',
    }
  },

  computed: {

  },
  created() {


  },
  methods:{
    //删除
    delRow(item){
      this.$confirm('确定删除此条记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePriceData({ppId:item.ppId}).then(()=>{
          this.getList();
          this.getCharts()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    changeItem(item){
      this.goods = item;
      if(item != ''){
        this.listQuery.goodsSn = item.name
      }else{
        this.listQuery.goodsSn = ''
      }
      this.handleSearchList();
    },

    getCalculatePrice(){
      calculatePrice({goodsLine:this.form.goodsName}).then((res)=>{
            this.form.standardPrice = res.price
            this.formula = res.formula
      })
    },

    init(type){
      this.listQuery.tab = type
      this.getList();
      this.getGoodsSnList();
      this.getCharts()
    },
    getGoodsSnList(){
      myPurchaseGoodSn({keyword:this.keyword,tab:this.listQuery.tab}).then((res)=>{
        this.goodsSnList = res.list
      })
    },
    changeGoodsSn(item){
      this.form.goodsName = item.goodsLine;
      this.form.goodsSn = item.name;
      this.getCalculatePrice()
    },
    showPop(type,item){
      this.popType = type;
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm))
      this.formula = ''
      this.title = '新增行情'
      this.form.goods = this.goods
      if(this.form.goods != ''){
        this.changeGoodsSn(this.goods)
      }

      if(type == 'edit'){
          this.form.goodsSn = item.goodsSn
          this.form.standardPrice= item.standardPrice
          this.form.marketPrice= item.marketPrice
          this.form.factoryCapacity= item.factoryCapacity
          this.form.factoryStock= item.factoryStock
          this.form.isFactoryRepair= item.isFactoryRepair
          this.form.repairRemark= item.repairRemark
          this.form.ppId= item.ppId
          this.form.goodsName = item.goodsName;
          this.form.notes = item.notes
          this.title = '编辑行情'
      }else{
        this.form.goodsSn = this.listQuery.goodsSn
      }
    },

    handleConfirm(){

      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          delete data.goods
          editPurchasePrice(data).then((res)=>{
            this.btnLoading = false;
            this.dialogVisible = false;
            this.getList()
            this.getCharts()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      });
    },

    handleClose(){
      this.dialogVisible = false
    },
    getCharts(){
      if(this.listQuery.goodsSn != ''){
        priceStatistics(this.listQuery).then((res) => {
          this.draw1(res.xData,res.yStandardPrice,res.yMarketPrice)
        })
      }
    },
    //绘制图表
    draw1(x, y1, y2) {
      let newArr = [...y1, ...y2]
      if (newArr.length > 1) {
        newArr.sort(function (a, b) {
          return a - b;
        });
      }
      let minNum = parseFloat(newArr[0])
      let maxNum = parseFloat(newArr[newArr.length - 1])
      // console.log(this.$echarts)
      let myChart = this.$echarts.init(document.getElementById('myChart'));
      // 绘制图表
      myChart.setOption({
        xAxis: {
          type: 'category',
          data: x
        },
        legend: {
          data: ['标准报价', '市场报价']
        },
        yAxis: {
          type: 'value',
          min: minNum,
          max: maxNum,
        },
        tooltip: {
          trigger: 'axis',
        },
        series: [
          {
            name:'标准报价',
            data: y1,
            type: 'line',
            smooth: true,

          },
          {
            name:'市场报价',
            data: y2,
            type: 'line',
            smooth: true,
          }
        ]
      });
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
      this.getCharts()
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let data = JSON.parse(JSON.stringify(this.listQuery))
      if(data.priceDate == null){
        data.priceDate = []
      }
      priceDataList(data).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
    },
  },
}
</script>

<style scoped lang="scss">
    .goodsSn-item{
        text-align: center;
        font-size:12px;
        line-height: 20px;
        padding:8px;
        border-bottom:1px solid #eee;
        cursor: pointer;
    }
    .choose.goodsSn-item{
      background: #409eff;
      color:#fff;
    }
</style>
